package club.dataresources.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AdminLoginFilter implements Filter {
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;

        String path = httpReq.getContextPath();
        String basePath = httpReq.getScheme() + "://" + httpReq.getServerName() + ":" + httpReq.getServerPort() + path + "/";
        String uri = httpReq.getRequestURI();
        HttpSession session = httpReq.getSession();

        //判断是否已经登录
        if (session.getAttribute("adminLoginFlag") == null) {
            //尚未登录，再判断url是否含有admin，如果含有则需要拦截，将重定向到登录页面
            if (uri.indexOf("admin") == -1 ||uri.indexOf("adminLogin") != -1 || uri.indexOf("login") != -1) {
                chain.doFilter(request, response);
            } else {
                System.out.println("=========adminLoginFlag为null====管理员尚未登录!将重定向到登录页面======");
                System.out.println("=======basePath======" + basePath);
                //response.getWriter().write("{\"status\":500,\"msg\":\"NO_LOGININ\"}");
                ((HttpServletResponse) response).sendRedirect("../login.html");
            }
        } else {
            System.out.println("=====adminLoginFlag=====管理员已经登录!处理通过======");
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
